import { RouteRecordRaw } from 'vue-router';

export default function useRoutes() {
  const routesUrl = import.meta.glob('@/pages/**/index.vue');
  const routes: RouteRecordRaw[] = [];

  for (const item of Object.keys(routesUrl)) {
    const urlArr = item.split('/').reverse();
    let name = urlArr[1];

    const route: RouteRecordRaw = {
      path: urlArr.length === 5 ? `/${name}` : name,
      name,
      component: () => import(item),
    };

    let mapRoutes = routes;
    let index = urlArr.length - 4;
    while (index > 0) {
      if (index === 1) {
        mapRoutes.push(route);
      } else {
        let findRoute = mapRoutes.find((item) => item.name === urlArr[index]);
        if (!findRoute?.children) {
          (findRoute as RouteRecordRaw).children = [];
        }

        mapRoutes = findRoute?.children as RouteRecordRaw[];
        findRoute = undefined;
      }

      index--;
    }
  }

  return routes;
}
